package com.woniuxy.aliyunoss.controller;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;

import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.woniuxy.commons.utils.ResStatus;
import com.woniuxy.commons.utils.ResponseResult;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/aliyunoss/sms")
public class SmsController {
    @Value("${sms.accessKeyId}")
    private String accessKeyId;
    @Value("${sms.accessSecret}")
    private String accessSecret;
    @Value("${sms.signName}")
    private String signName;
    @Value("${sms.templateCode}")
    private String templateCode;

    @GetMapping("/{phone}/{code}")
    public ResponseResult send(@PathVariable("phone") String phone,@PathVariable("code") String code){
        System.out.println("电话:"+phone+",验证码:"+code);
        if (StringUtils.isEmpty(phone)) {
            throw new RuntimeException("手机号码不能为空");
        }
        if (StringUtils.isEmpty(code)) {
            throw new RuntimeException("验证码不能为空");
        }
        // 初始化acsClient,暂不支持region化
        IClientProfile profile = DefaultProfile.getProfile("cn-chengdu", accessKeyId, accessSecret);
        IAcsClient acsClient = new DefaultAcsClient(profile);
        // 组装请求对象
        SendSmsRequest request = new SendSmsRequest();
        // 待发送手机号
        request.setPhoneNumbers(phone);
        // 发送内容
        request.setTemplateParam("{\"code\":\"" + code + "\"}");
        request.setSignName(signName);
        request.setTemplateCode(templateCode);

        SendSmsResponse sendSmsResponse = null;
        try {
            sendSmsResponse = acsClient.getAcsResponse(request);
        } catch (ClientException e) {
            e.printStackTrace();
        }
        if(sendSmsResponse.getCode()!= null && "OK".equals(sendSmsResponse.getCode())){
            return new ResponseResult(200,"短信发送成功",null, ResStatus.SUCCESS);
        }else {
            return new ResponseResult(200,"短信发送失败",sendSmsResponse.getMessage(), ResStatus.FAIL);
        }
    }
}